const Utils = {
  http: jsBridge.http,
  isEmpty: function (value) {
    let type = Object.prototype.toString.call(value)
    switch (type) {
    case '[object Undefined]':
    case '[object Null]':
      return true
    case '[object Array]':
      return value.length === 0
    case '[object Object]':
      return Object.keys(value).length === 0
    default:
      return (value + '').trim() === ''
    }
  },
  notEmpty: function (value) {
    return !this.isEmpty(value)
  },
  isUndefined: function (obj) {
    return Object.prototype.toString.call(obj) === '[object Undefined]'
  },
  isArray: function (obj) {
    return Object.prototype.toString.call(obj) === '[object Array]'
  },
  isObject: function (obj) {
    return Object.prototype.toString.call(obj) === '[object Object]'
  },
  isRegExp: function (obj) {
    return Object.prototype.toString.call(obj) === '[object RegExp]'
  },
  isString: function (obj) {
    return Object.prototype.toString.call(obj) === '[object String]'
  },
  isNumber: function (obj) {
    return Object.prototype.toString.call(obj) === '[object Number]'
  },
  isFun: function (obj) {
    return Object.prototype.toString.call(obj) === '[object Function]'
  },
  /*反序列化json*/
  fromJson: function (json) {
    return JSON.parse(json)
  },
  //获取url参数，地址栏上面的参数
  getParam: function (name) {
    let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)') //构造一个含有目标参数的正则表达式对象
    let r = window.location.search.substr(1).match(reg)  //匹配目标参数
    return r !== null ? unescape(r[2]) : null //返回参数值
  },
  addMethod: function (object, name, fn) {
    let old = object[name]
    object[name] = function () {
      if (fn.length === arguments.length) {
        return fn.apply(this, arguments)
      } else if (typeof old === 'function') {
        return old.apply(this, arguments)
      }
    }
  },
  loadJS: function (src, callback) {//动态加载JS
    return new Promise(resolve => {
      const oScript = document.createElement('script')
      oScript.type = 'text/javascript'
      oScript.src = src
      document.body.appendChild(oScript)
      oScript.onload = resolve
    })
  },
  loadCSS: function (src) {//动态加载CSS
    return new Promise(resolve => {
      const addFile = document.createElement('link')
      addFile.type = 'text/css'
      addFile.rel = 'stylesheet'
      addFile.media = 'screen'
      addFile.href = src
      document.body.appendChild(addFile)
      addFile.onload = resolve
    })
  },
  throttle: function (fn, gapTime) {/*节流函数，用于指定方法多久执行一次*/
    let _lastTime = null
    return function () {
      let _nowTime = +new Date()
      if (_nowTime - _lastTime > gapTime || !_lastTime) {
        fn()
        _lastTime = _nowTime
      }
    }
  },
  debounce: function (fn, wait) {/*防抖函数，可以用于输入延时请求*/
    let timer = null
    return function () {
      let context = this
      let args = arguments
      if (timer) {
        clearTimeout(timer)
        timer = null
      }
      timer = setTimeout(function () {
        fn.apply(context, args)
      }, wait)
    }
  },
  dealUndefined: function (val) {
    return val ? val : ''
  },
  dealNumber: function (num) {
    return Utils.isEmpty(num) ? 0 : num
  },
  openFile: function (val) {
    window.open('http://rwenzori.rmbtoglobal.com/view/web/viewer.html?file=' + encodeURI(val))
  },
  openWord: function (val) {
    window.open('https://view.officeapps.live.com/op/view.aspx?src=' + encodeURI(val))
  },
  //获取随机数
  getRandomFrom: function (lowerValue, upperValue) {
    return Math.floor(Math.random() * (upperValue - lowerValue + 1) + lowerValue)
  },
  sbhAdaptive: function () {//状态栏自适应
    // var sbh = jsBridge.getStatusBarHeight();
    const sbh = systemConfig.statusBarHeight,
      wrapperHeight = sbh + dict.NAV_HEIGHT()
    $('.status-bar').css({
      height: sbh + 'rem'
    })
    $('.nav-bar').css({
      top: sbh + 'rem'
    })
    $('.placeholder-top').css({
      height: wrapperHeight + 'rem',
      overflow: 'hidden'
    })
    $('.inside-warp').css({
      top: wrapperHeight + 'rem'
    })
  },
  barAdaptive: function (className, height) {//状态栏自适应
    let sbh = systemConfig.statusBarHeight
    $('.' + className).css({
      top: (sbh + height) + 'rem'
    })
  },
  goWordDetail: function (data) {
    Utils.stopBubbling()
    switch (parseInt(data.type)) {
    case 1: // 产业链详情
      Server.industrialDetail.getChainByKey({keyWords: data.word}).then(function (item) {
        // 跳转至产业链详情
        if (item.pageUrl) {
          item.pageUrl = item.pageUrl.startsWith('/') ? item.pageUrl.substring(1) : item.pageUrl
          jsBridge.openWindow(item.pageUrl, {}, {noBar: false})
        } else { // 可跳转至指定页面
          goSearchPage(data.word)
          //  jsBridge.openWindow('html/comment/no-power.html?type=1', {}, {noBar: false})
        }
      })
      break
    case 3: //跳转债券
      Server.absList.searchByKey({
        commons: {},
        datas: {
          keyWord: data.word,
          securityType: 'ABS',
          filterExpired: false
        }
      }).then(function (item) {
        if (item.data && item.data.length > 0) {
          Promise.all([
            Server.absDetail.quotations({
              commons: {},
              datas: {
                limitCount: 1,
                pageNum: 1,
                timeFrom: null,
                idFrom: null,
                timeTo: null,
                idTo: null,
                quotationType: 0,
                type: 2, // 0: 按 filter 里的筛选条件进行筛选， 2: 按 search 里指定债券id进行筛选
                filter: {
                  basicAssets: [],
                  priorityClass: [],
                  issuerRating: [],
                  bondRatingMatch: [],
                  secuMarkets: [],
                  terms: []
                },
                search: {
                  securityId: item.data[0].id
                },
              },
            }),
            Server.absDetail.quotations({
              commons: {},
              datas: {
                limitCount: 1,
                pageNum: 1,
                timeFrom: null,
                idFrom: null,
                timeTo: null,
                idTo: null,
                quotationType: 1,
                type: 2, // 0: 按 filter 里的筛选条件进行筛选， 2: 按 search 里指定债券id进行筛选
                filter: {
                  basicAssets: [],
                  priorityClass: [],
                  issuerRating: [],
                  bondRatingMatch: [],
                  secuMarkets: [],
                  terms: []
                },
                search: {
                  securityId: item.data[0].id
                },
              },
            })]).then(([absData1, absData2]) => {
            if (absData1.data && absData1.data.items.length > 0) {
              jsBridge.openWindow('html/data/abs-detail.html?securityId=' + absData1.data.items[0].securityId + '&securityCode=' + absData1.data.items[0].securityCode + '&type=0', {}, {noBar: false})
            } else {
              if (absData2.data && absData2.data.items.length > 0) {
                jsBridge.openWindow('html/data/abs-detail.html?securityId=' + absData2.data.items[0].securityId + '&securityCode=' + absData2.data.items[0].securityCode + '&type=1', {}, {noBar: false})
              } else {
                goSearchPage(data.word)
                //jsBridge.openWindow('html/comment/no-power.html?type=3', {}, {noBar: false})
              }
            }
          })
        } else {
          goSearchPage(data.word)
          //jsBridge.openWindow('html/comment/no-power.html?type=3', {}, {noBar: false})
        }
      })
      break
    case 2:
    case 6:
      //股票行情
      jsBridge.openStock(data.exchange, data.stockCode)
      break
    case 5:
      Server.tableDetail.getChartsInfoByKey({keyWords: data.word}).then(function (item) {
        if (item.chartsInfo && item.chartsInfo.chartsCode && item.chartsInfo.title) {
          //跳转图表详情
          jsBridge.openWindow('html/data/table-detail.html?menuCode=' + item.chartsInfo.chartsCode + '&appName=' + item.chartsInfo.title, {}, {noBar: false})
        } else {
          //跳转至引导页
          // jsBridge.openWindow('html/comment/no-power.html?type=5', {}, {noBar: false})
          goSearchPage(data.word)

        }
      })
      break
    case 4:
      // 公司实体
      goSearchPage(data.word)
      //jsBridge.openWindow('html/comment/no-power.html?type=4', {}, {noBar: false})
      break
    default:
      goSearchPage(data.word)
      //jsBridge.openWindow('html/comment/no-power.html?type=6', {}, {noBar: false})
      break
    }
  },
  // 跳转至搜索页
  goSearchPage: function (key) {
    key = key ? encodeURIComponent(Utils.replaceAll(key, '%', '%25')) : ''
    jsBridge.openWindow('html/search/search.html?key=' + key, {}, {noBar: false})
  },
  // 跳转资讯详情
  goDetail: function (data, that) {
    let infoId, time, infoType, funcCode, bsId, resourceType, chapterId
    if (Utils.isObject(data)) {
      infoType = data.infoType
      infoId = Utils.notEmpty(data.infoId) ? data.infoId : ''
      funcCode = Utils.notEmpty(data.funcCode) ? data.funcCode : ''
      bsId = Utils.notEmpty(data.bsId) ? data.bsId : ''
      chapterId = Utils.notEmpty(data.chapterId) ? data.chapterId : ''
      resourceType = Utils.notEmpty(data.resourceType) ? data.resourceType : ''
      time = Utils.notEmpty(data.time) ? data.time : ''
    }
    switch (parseInt(infoType)) {
    case 1:
    case 3:
    case 9:
      $(that).find('.info-list-title').addClass('info-list-read')
      jsBridge.openWindow('html/info/info-detail.html?infoId=' + infoId + '&infoType=' + infoType, {}, {noBar: false})
      break
    case 2: {
      //let vUrl = 'html/video/video-live.html?infoId=' + infoId
      //if (resourceType === '2') {
      //  vUrl = 'html/video/video-vod.html?infoId=' + infoId
      //}
      //jsBridge.callBridge('openVideo', {infoId: infoId, infoType: infoType, resourceType: resourceType})

      jsBridge.openVideo({infoId: infoId, infoType: infoType, resourceType: resourceType}).then(function () {
        let that = $('.readCnt_' + infoId)
        if (that) {
          //获取当前对象内容
          let rt = that.html()
          rt = Utils.replaceAll(rt, ',', '')
          that.html(parseInt(rt) + 1)
        }

        if (pm) {
          pm.readCnt++
        }
      })
      break
    }
    case 4: {
      jsBridge.openWindow('html/home/stock-detail.html?infoId=' + infoId + '&infoType=' + infoType, {}, {noBar: false})
      break
    }
    case 7: {
      jsBridge.openWindow('html/info/flash-detail.html?infoId=' + infoId + '&infoType=' + infoType, {}, {noBar: false})
      break
    }
    case 8: {
      jsBridge.openWindow('html/research/report-detail.html?infoId=' + infoId + '&infoType=' + infoType, {}, {noBar: false})
      break
    }
    default:
      break
    }

  },
  openPdf: function (url, title) {
    jsBridge.openPdf(url, title)
  },
  goCommentList: function (data) {
    jsBridge.openWindow('html/comment/comment-list.html?infoId=' + data.infoId + '&infoType=' + data.infoType, {}, {noBar: false})
    stopBubbling()
  },
  exchangeTabPage: function (page) {
    jsBridge.callBridge('exchangeTabPage', {page: page})
  },
  clickBack: function () {
    jsBridge.callBridge('goBack')
  },
  goLogin: function () {
    jsBridge.callBridge('openLogin')
  },
  goRegister: function () {
    jsBridge.openWindow('html/login/register.html')
  },
  setUserHeadImg: function () {
    if (Utils.notEmpty(user) && Utils.notEmpty(user.headUrl)) {
      $('.head-img').attr('src', user.headUrl)
    } else {
      $('.head-img').attr('src', '../images/user/default-icon2.png')
    }
  },
  toast: function (msg) {
    jsBridge.callBridge('toast', {msg: msg})
  },
  goShare: function (item) {
    jsBridge.share(item).then(data => {
      Utils.toast(data.message)
    }).catch(err => {
      console.error(err)
    })
  },
  goHelpCenterDetail: function (questionId) {
    jsBridge.openWindow('html/user/help-detail.html?questionId=' + questionId, {}, {noBar: false})
  },
  goFeedBackDetail: function (messsageId) {
    jsBridge.openWindow('html/user/feedback-detail.html?messageId=' + messsageId, {}, {noBar: false})
  },
  removeHtmlStype(content) {
    if (content) {
      return content.replace(/<[^>]+>/g, '')
    } else {
      return content
    }
  },
  retainData: function (val) {
    if (Utils.isEmpty(val)) {
      return ''
    } else {
      return val.replace(/[^\d.]/g, '')
    }
  },
  replaceAll: function (str, oldStr, newStr) {
    // 字符串处理 全部替换
    return str.replace(new RegExp(oldStr, 'gm'), newStr)
  },
  replaceEnter: function (str) {
    //字符串处理 空格和换行符处理
    if (Utils.isEmpty(str)) {
      return str
    }
    str = Utils.replaceAll(str, '\r\n', '<br>')
    str = Utils.replaceAll(str, '\n', '<br>')
    str = Utils.replaceAll(str, ' ', '&nbsp;')
    return str
  },
  dealKeyWord: function (desc, keyWord) {
    if (desc && keyWord) {
      desc = desc.replace(keyWord, '<em>' + keyWord + '</em>')
    }
    return desc
  },
  phoneCheck: function (phone) {
    let reg = /^[1][3,4,5,7,8][0-9]{9}$/
    let regh = /^[0][0][0-9]{11}$/
    if (phone !== null && phone.length === 11 && reg.test(phone)) {
      return true
    }

    return phone !== null && phone.length === 13 && regh.test(phone)
  },
  thousands: function (num) {
    if (num !== null) {
      let str = num.toString()
      let reg = str.indexOf('.') > -1 ? /(\d)(?=(\d{3})+\.)/g : /(\d)(?=(?:\d{3})+$)/g
      return str.replace(reg, '$1,')
    } else {
      return ''
    }
  },
  numberFormat: function (number, decimals, thousands_sep) {
    //金额格式化，四舍五入
    number = (number + '').replace(/[^0-9+-Ee.]/g, '')
    let n = !isFinite(+number) ? 0 : +number,
      prec = !isFinite(+decimals) ? 2 : Math.abs(decimals),
      sep = thousands_sep === 'NO' ? '' : ',',
      s = '',
      toFixedFix = function (n, prec) {
        let k = Math.pow(10, prec)
        return '' + Math.ceil(n * k) / k
      }

    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.')
    let re = /(-?\d+)(\d{3})/
    while (re.test(s[0])) {
      s[0] = s[0].replace(re, '$1' + sep + '$2')
    }

    if ((s[1] || '').length < prec) {
      s[1] = s[1] || ''
      s[1] += new Array(prec - s[1].length + 1).join('0')
    }
    return s.join('.')
  },
  emailCheck: function (email) {
    let reg = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/
    return reg.test(email)
  },
  pwdCheck: function (pwd) {
    let reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,21}$/
    return reg.test(pwd)
  },
  checkPhoneSystem: function () {//校验环境
    if (platform === 'ios') {
      return 1
    } else if (platform === 'android') {
      return 2
    } else {
      return 3
    }
  },
  // 阻止冒泡事件
  stopBubbling: function () {
    let e = window.event
    if (e.stopPropagation) {
      e.stopPropagation() //阻止事件 冒泡传播
    } else {
      e.cancelBubble = true //ie兼容
    }
  },
  goFeedbackSchedule: function () {
    jsBridge.openWindow('html/user/feedback-schedule.html', {}, {})
  },
  groupArr:function (list,field){
    let obj = {}
    for (let i = 0; i < list.length; i++) {
      for (let item in list[i]) {
        if (item === field) {
          obj[list[i][item]] = {
            list: obj[list[i][field]] ? obj[list[i][field]].list : [],
            type: list[i].type
          }
        }
      }
      obj[list[i][field]].list.push(list[i])
    }
    let att = []
    for (let item in obj) {
      att.push({list: obj[item].list})
    }
    return att
  },

  //表情包校验
  emojiJudge:function(text){
    // eslint-disable-next-line no-misleading-character-class
    let emoji = /[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/ig
    if (emoji.test(text)){
      return true
    } else {
      return false
    }
  },
  formatNumber: function(num) {
    if (typeof num !== 'number' || isNaN(num)) {
      return num;
    }

    if (num >= 0 && num <= 999) {
      return num.toString();
    } else if (num >= 1000 && num < 10000) {
      return Math.floor(num / 1000) + 'k';
    } else if (num >= 10000) {
      return Math.floor(num / 10000) + 'w';
    }

    return num.toString();
  }
}

const Cache = {
  set: function (key, value) {
    if (Utils.isEmpty(key)) {
      console.error('参数key错误，key不能为空。')
    } else {
      jsBridge.callBridge('setData', {key: key, value: JSON.stringify(value)})
    }
  },
  get: function (key) {
    return jsBridge.callBridge('getData', {key: key})
  },
  del: function (key) {
    jsBridge.callBridge('delData', {key: key})
  },
  //清除所有缓存，但保留arr里的元素
  clear: function () {
    jsBridge.clearData()
  }
}

// 跳转资讯详情
window.goDetail = Utils.goDetail
window.openPdf = Utils.openPdf
window.goCommentList = Utils.goCommentList
window.goDataGo = Utils.goDataGo
window.exchangeTabPage = Utils.exchangeTabPage
window.clickBack = Utils.clickBack
window.stopBubbling = Utils.stopBubbling
window.goWordDetail = Utils.goWordDetail
window.goSearchPage = Utils.goSearchPage

